<script setup lang="ts">
import { ref, onMounted } from 'vue'
import ResourceUpload from '@/components/resource/ResourceUpload.vue'
import ResourceList from '@/components/resource/ResourceList.vue'
import { getUserMusic } from '@/api/source'
import { ElMessage } from 'element-plus'
import type { Music } from '@/stores/player'

// 已上传的音乐列表
const musicList = ref<Music[]>([])

// 获取音乐列表
const fetchMusicList = async () => {
  try {
    const result = await getUserMusic()
    if (result.success) {
      musicList.value = result.data.map(item => ({
        id: item.id.toString(),
        title: item.title,
        artist: item.artist,
        cover: item.cover,
        url: item.url,
        lrc: item.lrc,
        duration: item.duration
      }))
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    console.error('获取音乐列表失败:', error)
    ElMessage.error('获取音乐列表失败')
  }
}

// 刷新列表
const refreshList = () => {
  fetchMusicList()
}

// 控制上传区域的显示
const showUpload = ref(true)

// 切换到上传区域
const handleShowUpload = () => {
  showUpload.value = true
  document.querySelector('.upload-section')?.scrollIntoView({ 
    behavior: 'smooth' 
  })
}

onMounted(() => {
  fetchMusicList()
})
</script>

<template>
  <div class="resource-page">
    <!-- 上传表单 -->
    <ResourceUpload 
      v-show="showUpload"
      @upload-success="refreshList" 
    />

    <!-- 已上传音乐列表 -->
    <ResourceList 
      :music-list="musicList" 
      @delete-success="refreshList"
      @show-upload="handleShowUpload"
    />
  </div>
</template>

<style scoped lang="scss">
.resource-page {
  padding: 20px;
}
</style> 